<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Prize as PrizeModel;
use app\common\model\PrizeLog;

/**
 * 首页接口
 */
class Prize extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 获取奖品列表
     */
    public function getlist()
    {
        $prize = PrizeModel::all();
        $this->success('', $prize);
    }

    /**
     * 抽奖
     */
    public function lucky()
    {
        $param = $this->request->post();

        $uid = $this->auth->getUser()->id;
        // 传递过来的参数进行抽奖
        // 没有抽中奖品
        if ($param['keyword'] == 'null ') {
            // 一天只可以抽两次
            $data = [
                'user_id' => $uid,
            ];
            $prize_log_num = PrizeLog::where($data)
                ->whereTime('createtime', 'd')
                ->count();
            if ($prize_log_num >= 2) {
                $this->error('明天继续！');
            } else {
                $data['prize_id'] = 0;
                $prize_log = PrizeLog::create($data);
                if (!$prize_log) $this->error('抽奖失败');
            }
            $this->success('成功');

        } else {
            // 抽中奖品
            $prize = PrizeModel::where(['keyword' => $param['keyword']])->find();
            if (!$prize) $this->error('未查询到该奖品');
            if ($prize->nums > 0) {

                // 一天只可以抽两次
                $data = [
                    'user_id' => $uid,
                ];
                $prize_log_num = PrizeLog::where($data)
                    ->whereTime('createtime', 'd')
                    ->count();
                if ($prize_log_num >= 2) {
                    $this->error('明天继续！');
                } else {
                    $data['prize_id'] = $prize['id'];
                    $prize_log = PrizeLog::create($data);
                    if (!$prize_log) $this->error('抽奖失败');
                }

                //
                $prize->nums = $prize->nums - 1;
                if (!$prize->save()) $this->error('商品数量保存失败');
                $this->success('成功');

            } else {
                $this->error('奖品没了！');
            }
        }


    }
}
